package com.msdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msdp.dto.LoginFormDTO;
import com.msdp.dto.Result;
import com.msdp.dto.UserDTO;
import com.msdp.entity.User;
import com.msdp.mapper.UserMapper;
import com.msdp.service.EmailService;
import com.msdp.service.IUserService;
import com.msdp.utils.RegexUtils;
import com.msdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.msdp.utils.MessageConstants.*;
import static com.msdp.utils.RedisConstants.*;
import static com.msdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private static final String CHAT_LIST = "chat:";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private EmailService emailService;

    /**
     * 发送手机验证码
     * @param phone
     * @param session
     */
    @Override
    public Result sendPhoneCode(String phone, HttpSession session) {
        // 1. 校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            // 2. 不符合
            return Result.fail(PHONE_PATTERN_ERROR);
        }
        // 3. 符合->生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4. 保存验证码到Redis
        String key = LOGIN_CODE_KEY + phone;
        redisTemplate.opsForValue().set(key, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // TODO 使用第三方平台发送验证码
        // 5. 发送验证码
        log.info("发送短信验证码成功：{}", code);

        //返回ok
        return Result.ok();
    }

    @Override
    public Result sendEmailCode(String email, HttpSession session) {
        // 1. 校验手机号
        if(RegexUtils.isEmailInvalid(email)){
            // 2. 不符合
            return Result.fail(EMAIL_PATTERN_ERROR);
        }
        // 3. 符合->生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4. 保存验证码到Redis
        String key = LOGIN_CODE_KEY + email;
        redisTemplate.opsForValue().set(key, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // TODO 使用第三方平台发送验证码
        // 5. 发送验证码
        emailService.sendVerificationCode(email, code);
        log.info("发送短信验证码成功：{}", code);

        //返回ok
        return Result.ok();
    }

    /**
     * 用户登录注册功能（Redis实现）
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        // 校验邮箱
        if(RegexUtils.isEmailInvalid(phone)){
            return Result.fail(EMAIL_PATTERN_ERROR);
        }

        String code = loginForm.getCode();
        User user = new User();
        if(StrUtil.isNotBlank(code)) {
            // 1. 校验验证码
            String key = LOGIN_CODE_KEY + phone;
            String cacheCode = redisTemplate.opsForValue().get(key);
            if (cacheCode == null || !cacheCode.equals(code)) {
                // 2. 错误->直接返回错误信息
                return Result.fail(CODE_ERROR);
            }
            // 3. 正确->根据手机号查询用户
           user = query().eq("phone", phone).one();

            // 4. 不存在->新增用户数据
            if (user == null) {
                user = createUserWithPhone(phone);
            }
        }
        String passWord = loginForm.getPassword();
        if (StrUtil.isNotBlank(passWord)){
            user = lambdaQuery().eq(User::getPhone, phone).one();
            if(user == null || !user.getPassword().equals(passWord)){
                return Result.fail(USER_ERROR);
            }
        }

        // 5. 保存到Redis中
        // 5.1 生成随机token，作为登录令牌
        String token = UUID.randomUUID().toString(true);

        // 5.2 将User转为HashMap进行存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 自定义转换类型格式，将待转换的bean中所有字段转为String类型
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, filedValue) -> filedValue.toString()));
        redisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, map);
        // 设置token有效期
        redisTemplate.expire( LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);

        // 6. 返回token到前端
        return Result.ok(token);
    }

    /**
     * 登出功能
     * @return
     */
    @Override
    public Result logout() {
        return null;
    }
    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public Result getUserById(Long userId) {
        User user = getById(userId);
        return Result.ok(user);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 获取当前年月
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + date;
        // 3. 获取当前日期为本月第几天
        int dayOfMonth = now.getDayOfMonth();
        // 4. 写入bitmap签到
        redisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        // 5. 返回
        return Result.ok();
    }

    /**
     * 统计用户连续签到天数
     * @return
     */

    @Override
    public Result signCount() {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 获取当前年月
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + date;
        // 3. 获取当前日期为本月第几天
        int dayOfMonth = now.getDayOfMonth();
        // 4. 获取本月截至今天位置的所有签到记录，返回为十进制数字
        // BITFIELD key GET u dayOfMonth 0
        List<Long> result = redisTemplate.opsForValue()
                .bitField(
                        key,
                        BitFieldSubCommands.create()
                                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if(result == null || result.isEmpty()){
            return Result.ok(0);
        }

        Long num = result.get(0);
        if(num == null || num == 0){
            return Result.ok(0);
        }
        // 5. 循环遍历
        int count = 0;
        while (true){
            // 5.1 数字与1做与运算，得到数字最后一个bit位
            if((num & 1) == 0){
                // 5.2 判断bit位是否为0

                // 5.3 如果为0说明未签到，结束
                break;
            }else {
                // 5.4 如果为1说明已签到，计数器+1
                count++;
            }
            // 5.5 数字右移移位，抛弃最后一个bit位继续下一个bit位
            num >>>= 1;
        }

        return Result.ok(count);
    }
    /**
     * 用户是否签到
     * @return
     */
    @Override
    public Result isSign() {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 获取当前日期
        LocalDate now = LocalDate.now();
        String month = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        // 3. 拼接key
        String key = USER_SIGN_KEY + userId + month;
        // 4. 判断用户是否签到
        Boolean bit = redisTemplate.opsForValue().getBit(key, dayOfMonth - 1);
        // 5. 返回
        return Result.ok(bit);
    }

    /**
     * 根据id批量查询用户
     * @return
     */
    @Override
    public List<User> getUsersById() {
        Long userId = UserHolder.getUser().getId();
        String key = CHAT_LIST + userId;
        Set<String> members = redisTemplate.opsForSet().members(key);
        if(members == null || members.isEmpty()){
            return Collections.emptyList();
        }
        List<Long> ids = new ArrayList<>();
        for (String member : members) {
            ids.add(Long.valueOf(member));
        }
        return listByIds(ids);
    }

    /**
     * 根据手机号新建用户
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword("123321");
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }

}
